package com.etl.hadoop.etl.input;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.etl.hadoop.etl.IConstants;

public class QueryParser {
   
   private static Map<String,Document> dom = new HashMap<String,Document>();
   
   private QueryParser(String inputfile){
	   DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	   
		DocumentBuilder db = null;
		try {
			db = dbf.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		   try {
			dom.put(inputfile,db.parse(inputfile));
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	 
   }
   
   public synchronized static Document getInstance(String inputfile){
	   
	    if(dom.containsKey(inputfile)){
	    	return dom.get(inputfile);
	    }
	    else{
	    	QueryParser q = new QueryParser(inputfile);
	    	return dom.get(inputfile);
	    }
	    
   }
   
   public static ArrayList<String> getSelectColoumns(String inputfile ){
	   Document dom = getInstance(inputfile);
	   Element elem = dom.getDocumentElement();
	   ArrayList<String> selectList = new ArrayList<String>();
	   NodeList nl = elem.getElementsByTagName(IConstants.SELECT);
	   if(nl != null && nl.getLength() > 0){
		   for (int i =0; i< nl.getLength() ; i++){
			   Element s = (Element) nl.item(i);
			   String cname  =getTextValue(s,IConstants.COLUMN ); 
			   selectList.add(cname);
			   
		   }
	   }
	   return selectList;
   }
   
	private static String getTextValue(Element ele, String tagName) {
		String textVal = null;
		NodeList nl = ele.getElementsByTagName(tagName);
		if(nl != null && nl.getLength() > 0) {
			Element el = (Element)nl.item(0);
			textVal = el.getFirstChild().getNodeValue();
		}

		return textVal;
	}
	
	
	public static void main(String args[]){
	 ArrayList<String> a = QueryParser.getSelectColoumns("/home/sasanka/dev/test.xml");
	 for(String ar : a){
		 System.out.println(ar);
	 }
	}

}
